import util from "../../utils/util";
import answerUtil from "../../utils/answerUtil";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    answer:[],//选项
    questionAnswer:null,//答案
    chooseNum: null,
    questionIndex:0,//当前题型索引
    topicContent:[],//当前题型所有题目
    count: 0,//题目数量
    currentIndex: 0, // 当前题目索引
    currentTopic: null, // 当前展示的题目
    title:'',//标题
    question:'',//问题
    countdownTime: 0, // 倒计时时间
    countdownInterval: null, // 存储 interval ID
    questionStartTime: null,//记录题目开始时间
    answerRecords: [],//答题记录
  },
  onLoad(){
    this.getTopicData();
    // 初始化时加载已有的答题记录
    const savedAnswerRecords = answerUtil.getAnswerRecords();
    this.setData({
      answerRecords: savedAnswerRecords
    });
  },
  // 获取总题目
  getTopicData(){
    const questionIndex = wx.getStorageSync('questionInfo').questionNumber;
    const {count,topicContent} = util.getData(questionIndex);
    this.setData({
      count,
      topicContent,
      questionIndex
    })
    this.getCurrentTopicData();
  },
  // 获取当前题目
  getCurrentTopicData(){
    const {topicContent,currentIndex} = this.data;
    const currentTopic = topicContent[currentIndex];// 当前展示的题目
    const answer = currentTopic.optionList;//选项
    const questionAnswer = currentTopic.questionAnswer;//答案
    const descArray = JSON.parse(currentTopic.describe); // 得到标题数组
    const title = descArray[0].content;// 标题数据
    const question = JSON.parse(currentTopic.answerSheet).content; // 得到问题数组
    const questionCountdown = JSON.parse(currentTopic.answerSheet).residenceTime;
    let countdownTime = parseInt(questionCountdown, 10) / 1000;//题目停留时长

    // 添加 NaN 检查，如果为 NaN 则设置默认值
    if (isNaN(countdownTime) || countdownTime <= 0) {
      countdownTime = 60; // 设置默认倒计时为60秒
    }
    
    this.setData({
      currentTopic,
      answer,
      questionAnswer,
      title,
      question,
      countdownTime,
      chooseNum: null,
      value:'',
      questionStartTime: new Date().getTime()
    });
    // 每道题目开始倒计时
    this.startCountdown();
  },
  // 倒计时
  startCountdown() {
    let that = this;
    let {count,currentIndex} = that.data;
    // 清除已有倒计时
    if (that.data.countdownInterval) {
      clearInterval(that.data.countdownInterval);
    }
    const interval = setInterval(() => {
      let newTime = that.data.countdownTime - 1;
      if (newTime > 0) {
        that.setData({
          countdownTime: newTime
        });
      } else {
        clearInterval(interval);
        // 倒计时结束，视为错误
        wx.showToast({
          title: '已超时',
          icon: 'none',
          duration: 1000
        });
        setTimeout(() => {
          // 使用共用方法创建并保存答题记录
          const newAnswerRecords = that.createAndSaveAnswerRecord(true);
          let totalCount = currentIndex + 1;
          that.setData({
            currentIndex:totalCount,
            answerRecords: newAnswerRecords
          })
          if (totalCount >= count) {
            let questionNumber = that.data.questionIndex + 1;
            const prevInfo = wx.getStorageSync('questionInfo') || {};
            wx.setStorageSync('questionInfo', {
              ...prevInfo,
              questionNumber
            });
            util.navigateByDesc(questionNumber);//跳转下一题
          } else {
            // 继续下一题
            that.getCurrentTopicData();
          }
        }, 1000);
      }
    }, 1000);
    that.setData({
      countdownInterval: interval
    });
  },
  onChoose(e) {
    let index = e.currentTarget.dataset.index;
    let {answer} = this.data;
    let value = answer[index].serialNumber;
    this.setData({
      chooseNum: index,
      value
    })
  },
  // 提交
  onSubmit() {
    let {count,currentIndex,value} = this.data;
    if (!value) return;
    // 使用共用方法创建并保存答题记录
    const newAnswerRecords = this.createAndSaveAnswerRecord(false, value);
    // 清除倒计时
    if (this.data.countdownInterval) {
      clearInterval(this.data.countdownInterval);
      this.setData({
        countdownInterval: null
      });
    }
    let totalCount = currentIndex + 1;
    this.setData({
      currentIndex:totalCount,
      answerRecords: newAnswerRecords
    })
    if (totalCount >= count) {
      let questionNumber = this.data.questionIndex + 1;
      const prevInfo = wx.getStorageSync('questionInfo') || {};
      wx.setStorageSync('questionInfo', {
        ...prevInfo,
        questionNumber
      });
      util.navigateByDesc(questionNumber);//跳转下一题
    } else {
      // 继续下一题
      this.getCurrentTopicData();
    }
   
  },
  // 处理答题记录
  createAndSaveAnswerRecord(isTimeout = false, userOption = '') {
    const {currentIndex, questionStartTime, topicContent, questionAnswer} = this.data;
    
    // 计算答题时间
    const endTime = new Date().getTime();
    const answerTime = answerUtil.calculateAnswerTime(questionStartTime, endTime);
    
    // 获取当前题目信息
    const currentTopic = topicContent[currentIndex];
    
    // 判断是否正确（超时视为错误）
    let isRight = 0;
    let option = '';
    
    if (!isTimeout) {
      option = userOption;
      isRight = (userOption === questionAnswer) ? 1 : 0;
    }
    
    // 创建答题记录
    const answerRecord = answerUtil.createAnswerRecord({
      qosId: currentTopic.questionId,
      anserTime: answerTime,
      isRight: isRight,
      option: option,
      classify: currentTopic.classify,
      stem: currentTopic.stem,
      accuracy: '',
      timeStemp: endTime.toString(),
      everyTxt: '',
      rightOption: currentTopic.questionAnswer,
      score: 0,
    });
    
    // 添加答题记录
    const newAnswerRecords = answerUtil.addAnswerRecord(answerRecord);
    
    return newAnswerRecords;
  },

  onUnload() {
    // 页面卸载时确保答题记录已保存
    answerUtil.saveAnswerRecords(this.data.answerRecords);
    // 清除倒计时
    if (this.data.countdownInterval) {
      clearInterval(this.data.countdownInterval);
      this.setData({ countdownInterval: null });
    }
  }
})